from PIL import Image, ImageDraw, ImageFont
import random
import string
from os.path import join
from apps.admin import ROOT_PATH, CAPTCHA_MODE
import hashlib
import time


# pip install Pillow==9.4.0


def generate_captcha_image(mylen=4):
    # 创建一个空白图像
    width = 120
    height = 40

    # 定义图片大小及背景颜色
    image = Image.new('RGB', (width, height), color=(243, 251, 254))

    # 创建一个ImageDraw对象
    d = ImageDraw.Draw(image)

    if CAPTCHA_MODE == 1:
        captcha_list = string.digits
    elif CAPTCHA_MODE == 2:
        captcha_list = string.ascii_uppercase
    else:
        captcha_list = string.ascii_uppercase + string.digits
    # 生成5位数的验证码文本
    captcha_text = ''.join(random.choices(captcha_list, k=mylen))

    # 计算适合的字体大小
    font_size = min(width, height) // (len(captcha_text) * 2)

    # 使用系统自带字体，或指定字体文件路径
    font_path = join(ROOT_PATH, "static/font/arial.ttf")  # "/data/project/flask_admin/admin/static/font/arial.ttf"
    fnt = ImageFont.truetype(font_path, 30)

    # 获取文本尺寸
    # text_width, text_height = d.textsize(captcha_text, font=fnt)
    left, top, right, bottom = d.textbbox((0, 0), captcha_text, font=fnt)
    text_width, text_height = right - left, bottom - top

    # 计算文本的位置，使其居中
    x = (width - text_width) // 2
    y = (height - text_height) // 2

    # print(CAPTCHA_MODE, captcha_list, captcha_text)
    d.text((x, y), captcha_text, font=fnt, fill=(157, 30, 76))

    # 添加干扰线条和噪点
    for _ in range(random.randint(3, 5)):
        start = (random.randint(0, image.width), random.randint(0, image.height))
        end = (random.randint(0, image.width), random.randint(0, image.height))
        d.line([start, end], fill=(random.randint(50, 200), random.randint(50, 200), random.randint(50, 200)))

    for _ in range(100):
        xy = (random.randrange(0, image.width), random.randrange(0, image.height))
        d.point(xy, fill=(random.randint(50, 200), random.randint(50, 200), random.randint(50, 200)))

    return image, captcha_text


# password完整加密
def encrypt_password_all(password):
    salt = "ttkan_cn"
    md5 = hashlib.md5(password.encode('utf8')).hexdigest()
    md5 = md5 + salt
    password = hashlib.md5(md5.encode('utf8')).hexdigest()
    return password


# password二次md5加密
def encrypt_password(password_md5, salt=''):
    if salt == '':
        salt = "ttkan_cn"
    
    md5 = password_md5 + salt
    password = hashlib.md5(md5.encode('utf8')).hexdigest()
    return password


def format_time(timestamp):
    datetime = ''
    if isinstance(timestamp, int) and timestamp > 0:
        time_local = time.localtime(timestamp)
        datetime = time.strftime("%Y-%m-%d %H:%M:%S", time_local)

    return datetime
